import store from '../store/index'
const baseUrl = store.state.baseUrl



export default {
  /**
   * url     请求地址
   * data    请求参数
   * method  请求类型 默认post
   */
  request(url, { data = {}, method = 'post' }) {
    uni.showLoading({
      title: '加载中'
    });
    return new Promise((resolve, reject) => {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.hideLoading()
        // reject({
        //   code: 41009,
        //   message: '请登录再操作!'
        // })
        store.dispatch("login");
        return
      }
      uni.request({
        url: baseUrl + url,
        data,
        method,
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': token
        },
        success(res) {
          if (res.data.code === 200) {
            resolve(res.data)
          }else if(res.data.code == -1){
            // reject({
            //   code: 41009,
            //   message: '请登录再操作!'
            // })
            store.dispatch("login");
          }else if(res.data.code == -101){
            uni.showModal({
              title: "提示",
              content: '请绑定手机号再操作!',
              success: function(res) {
                uni.switchTab({
                  url: "/pages/my/my"
                });
              }
            });
          } else {
            reject(res.data)
          }
        },
        fail(err) {
          reject({ message: '网络出差错了' })
        },
        complete() {
          uni.hideLoading();
        }
      });
    })
  },

  /**
   * count   选择图片张数
   */
  chooseImage(count = 3) {
    return new Promise((resolve, reject) => {
      uni.chooseImage({
        count,
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;  // 图片临时路径数组
          resolve(tempFilePaths)
        },
        fail(err) {
          reject(err)
        }
      })

    })
  },

  /**
   * count   选择文件数
   */
  chooseFile(count = 10) {
    return new Promise((resolve, reject) => {
      wx.chooseMessageFile({
        count,
        type: 'file',
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFiles
          const fileName = tempFilePaths[0].name
          let fileSize = tempFilePaths[0].size
          if(fileSize > 1024 && fileSize < 1048576){
            fileSize = (fileSize / 1024).toFixed(1) + 'K'
          }else if(fileSize > 1048576){
            fileSize = (fileSize / 1048576).toFixed(1) + 'M'
          }else if(fileSize < 1024){
            fileSize = fileSize + 'B'
          }
          // 循环上传
          tempFilePaths.forEach((element, index) => {
            uni.uploadFile({
              url: store.state.baseUrl + "util.wx_uploader", //仅为示例，非真实的接口地址
              filePath: element.path,
              name: "file",
              success: uploadFileRes => {
                const data = JSON.parse(uploadFileRes.data);
                const { filename, url } = data.data.list;
                // that.loadImg.push({ url, filename });
                // 第一个参数是下载地址， 第二个参数是文件名
                resolve({ url: url + filename, fileName, fileSize })
              },
              fail(err) {
                console.log(err);
              }
            });
          });
        }
      })

    })
  },

  /**
   * 微信支付
   * url     请求地址
   * data    请求参数
   * method  请求类型 默认post
   */

  pay(orderid) {
    return new Promise((resolve, reject) => {
      this.request('order.pay', {
        data: {
          op: 'addOrderPay',
          orderid,
          payment_type: 2
        }
      }).then((res) => {
        console.log(res.data.list);
        const { timeStamp, nonceStr, paySign, signType } = res.data.list.pay_parameter
        uni.getProvider({
          service: "payment",
          success: function (unires) {
            let payment = unires.provider[0];
            // 支付api
            uni.requestPayment({
              provider: payment,
              timeStamp,
              nonceStr,
              package: res.data.list.pay_parameter.package,
              signType,
              paySign,
              success: function (respon) {
                resolve(respon)
              },
              fail: function (error) {
                reject(error)
              }
            });
          }
        });
      })

    })

  }

}